package org.example.config;

import jakarta.servlet.http.Cookie;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.example.entity.ApiLog;
import org.example.repository.ApiLogRepository;
import org.example.util.JWTUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpMethod;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.util.ContentCachingRequestWrapper;
import org.springframework.web.util.ContentCachingResponseWrapper;

import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.time.LocalDateTime;
import java.util.Map;
@Component
public class LoginInterceptor implements HandlerInterceptor {

    @Autowired
    private ApiLogRepository apiLogRepository;
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 强制添加CORS头（确保即使拦截器拒绝也返回CORS头）
        response.setHeader("Access-Control-Allow-Origin", "http://8.134.109.140:8080");
        response.setHeader("Access-Control-Allow-Credentials", "true");

        if (HttpMethod.OPTIONS.matches(request.getMethod())) {
            response.setHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS");
            response.setHeader("Access-Control-Max-Age", "3600");
            response.setHeader("Access-Control-Allow-Headers", "*");
            response.setStatus(HttpServletResponse.SC_OK);
            return true;  // 注意这里要返回false
        }

        Cookie[] cookies = request.getCookies();
        String token = null;

        // 遍历 Cookie 查找 token
        if (cookies != null) {
            for (Cookie cookie : cookies) {
                if ("token".equals(cookie.getName())) {
                    token = cookie.getValue();
                    break;
                }
            }
        }

        // 如果 Cookie 中没有找到 token，尝试从 Header 中获取
        if (token == null) {
            token = request.getHeader("Authorization");
        }

        // 验证 token
        if (token != null) {
            try {
                // 获取所有的 Cookie
                ContentCachingRequestWrapper wrappedRequest = new ContentCachingRequestWrapper(request);
                ContentCachingResponseWrapper wrappedResponse = new ContentCachingResponseWrapper(response);

                wrappedRequest.setAttribute("startTime", System.currentTimeMillis());
                Map<String, Object> claims = JWTUtil.parseToken(token);
                String userId = (String) claims.get("Email");

                // 创建 ApiLog 对象并设置基本信息
                ApiLog apiLog = new ApiLog();
                apiLog.setUserId("账号"+userId);
                apiLog.setMethod(wrappedRequest.getMethod());
                apiLog.setUri(wrappedRequest.getRequestURI());
                apiLog.setRequestParams(wrappedRequest.getQueryString());
                apiLog.setStartTime(LocalDateTime.now());

                // 读取请求体
                byte[] requestBody = wrappedRequest.getContentAsByteArray();
                apiLog.setRequestBody(new String(requestBody, StandardCharsets.UTF_8));

                // 将 ApiLog 对象存储到请求属性中
                wrappedRequest.setAttribute("apiLog", apiLog);
                return true;
            } catch (Exception e) {
                response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
                response.getWriter().write("Invalid token");
                return false;
            }
        } else {
            response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
            response.getWriter().write("Token is missing");
            return false;
        }
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws IOException {

        ContentCachingRequestWrapper wrappedRequest = new ContentCachingRequestWrapper(request);
        ContentCachingResponseWrapper wrappedResponse = new ContentCachingResponseWrapper(response);

        // 将包装后的 response 存储到请求属性中
        request.setAttribute("cachedResponse", wrappedResponse);

        // 记录请求开始时间
        request.setAttribute("startTime", System.currentTimeMillis());
        // 获取请求开始时间
        long startTime = (Long) request.getAttribute("startTime");
        long endTime = System.currentTimeMillis();
        long duration = endTime - startTime;

        // 获取之前存储的 ApiLog 对象
        ApiLog apiLog = (ApiLog) request.getAttribute("apiLog");
        if (apiLog != null) {
            // 设置响应信息
            apiLog.setStatusCode(wrappedResponse.getStatus());
            apiLog.setEndTime(LocalDateTime.now());
            apiLog.setDuration(duration);

            // 读取响应体
            byte[] responseBody = wrappedResponse.getContentAsByteArray();
            apiLog.setResponseBody(new String(responseBody, StandardCharsets.UTF_8));

            // 保存到数据库
            apiLogRepository.save(apiLog);
        }
    }
}
